<template>
  <BaseDialog
    ref="baseDialogRef"
    :dialogTitle="title"
    dialogWidth="1000px"
    dialogConfirmButtonText="选择物料批次"
    :showDialogFoot="true"
    @dialogClosed="dialogClosed"
    @dialogSubmit="dialogSubmit"
  >
    <template #dialog_body>
      <MaterialBatchTable
        ref="tableRef"
        v-model:multipleSelection="multipleSelection"
        :showOperatorColumn="false"
        :showAddNewButton="false"
        :showDeleteButton="false"
        :showEditButton="false"
        :allowEditTableCell="false"
        :materialIdOfQuery="materialId"
      />
    </template>
  </BaseDialog>
</template>

<script setup lang="ts">
import BaseDialog from '@/components/base/dialog/BaseDialogComponent.vue';
import type { Material } from '@/types/interface/mes_interface';
import type { MaterialBatch } from '@/types/interface/wms_interface';
import MaterialBatchTable from '@/views/page/wms/materialbatch/IndexView.vue';
import { ElMessage } from 'element-plus';
import { nextTick, ref } from 'vue';
const emit = defineEmits(['afterSubmit', 'dialogClosed']);
// 接收父组件的值
interface Props {
  dialogWidth?: string; // 对话框宽度
  title?: string; // 对话框标题,前台传入，不用加入添加或编辑的文本。添加或编辑的文本由action属性决定
  multipleLimit?: number; //允许选择的最多数量
  materialId?: string; //物料id，不是必须，但是如果是必须则默认物料批次的查询条件固定位物料
}
const props = withDefaults(defineProps<Props>(), {
  title: '物料批次选择',
  multipleLimit: 1
});
//定义表格复选框。注意非必填字段
const multipleSelection = ref<MaterialBatch[]>([]); // 复选框选择的记录row
//物料表ref对象
const tableRef = ref();
const dialogClosed = () => {
  emit('dialogClosed');
};
const baseDialogRef = ref();
// 打开此对话框的函数
const openDialog = async () => {
  baseDialogRef.value.openDialog();
  await nextTick();
  //清空物料批次表原来的查询条件和选中的记录
  tableRef.value.clearQuery();
  tableRef.value.clearSelection();
  if (props.materialId) {
    tableRef.value.setQueryField('material.id', props.materialId);
  }
  await nextTick();
  await tableRef.value.loadTableList();
};
// 关闭此对话框的函数
const closeDialog = () => {
  baseDialogRef.value.closeDialog();
};
//对话框提交事件
const dialogSubmit = () => {
  let valid = true; //验证是否符合提交要求，默认符合
  if (multipleSelection.value.length == 0) {
    valid = false;
    ElMessage.error('请选择物料批次');
  }
  //如果是多选并且限制大于1
  if (multipleSelection.value.length > props.multipleLimit) {
    valid = false;
    ElMessage.error(`最多只能选择${props.multipleLimit}个物料批次`);
  }
  //如果符合提交规则
  if (valid) {
    emit('afterSubmit', multipleSelection.value);
    baseDialogRef.value.closeDialog();
  }
};
//清空表格选中的复选框
defineExpose({
  // 参考vue3官方文档，需要将函数暴露出去才能被父组件调用，setup模式是不暴露的
  openDialog,
  closeDialog
});
</script>

<style scoped></style>
